package com.lightjet.macross.base.auth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import javax.annotation.Resource;

/**
 * @author : lijia
 * @version : 1.0 2019-10-22 14:51
 * description : 认证服务器用户安全配置中心
 */

@EnableWebSecurity
public class WebSecurityConfigure extends WebSecurityConfigurerAdapter {

    @Resource(name="sysUserAuthServiceImpl")
    private UserDetailsService userAuthService;
    // 请配置这个，以保证在刷新Token时能成功刷新
/*    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        // 配置用户来源于数据库
        // 配置密码加密方式  BCryptPasswordEncoder，添加用户加密的时候请也用这个加密
        auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
    }*/

/*    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //auth.userDetailsService(userDetailsService()).passwordEncoder(new NoopPasswordEncoder());
        //auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("user_1").password(new BCryptPasswordEncoder().encode("123456")).roles("USER");

    }*/

/*    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //super.configure(auth);
        auth.inMemoryAuthentication()
                .withUser("zhangsan").password("{noop}123456").roles("VIP1","VIP2")
                .and()
                .withUser("lisi").password("{noop}123456").roles("VIP2","VIP3")
                .and()
                .withUser("wangwu").password("{noop}123456").roles("VIP1","VIP3");

    }*/


    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        /*auth.inMemoryAuthentication() //认证信息存储到内存中
                .passwordEncoder(passwordEncoder())
                .withUser("user").password(passwordEncoder().encode("123456")).roles("ADMIN");*/
        auth.userDetailsService(userAuthService).passwordEncoder(new NoopPasswordEncoder());

    }

    private PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //这里是用户user 的认证配置
    /*@Bean
    @Override
    protected UserDetailsService userDetailsService() {

        // 这里是添加两个用户到内存中去，实际中是从#下面去通过数据库判断用户是否存在
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();

        NoopPasswordEncoder passwordEncode = new NoopPasswordEncoder();
        String pwd = passwordEncode.encode("{noop}123456");
        manager.createUser(User.withUsername("user_1").password(pwd).authorities("USER").build());
        manager.createUser(User.withUsername("user_2").password(pwd).authorities("USER").build());
        manager.createUser(User.withUsername("zhangsan").password(pwd).authorities("USER").build());
        manager.createUser(User.withUsername("lisi").password(pwd).authorities("USER").build());
        manager.createUser(User.withUsername("wangwu").password(pwd).authorities("USER").build());
        return manager;


        // #####################实际开发中在下面写从数据库获取数据###############################
        // return new UserDetailsService() {
        // @Override
        // public UserDetails loadUserByUsername(String username) throws
        // UsernameNotFoundException {
        // // 通过用户名获取用户信息
        // boolean isUserExist = false;
        // if (isUserExist) {
        // //创建spring security安全用户和对应的权限（从数据库查找）
        // User user = new User("username", "password",
        // AuthorityUtils.createAuthorityList("admin", "manager"));
        // return user;
        // } else {
        // throw new UsernameNotFoundException("用户[" + username + "]不存在");
        // }
        // }
        // };

    }*/

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http.csrf().disable().requestMatchers().anyRequest().and().authorizeRequests()
                .antMatchers("/oauth/**","/images/**","/css/**","/js/**","/ssologin","/fonts/**","/captcha","/wrappwd")
                .permitAll();
        // @formatter:on
    }

    @Override
    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /*@Bean
    public UserDetailsService userDetailsService(){
        return  new UserDetailsService() {//这里一般都是在业务层，实现UserDetailsService中loadUserByUsername(String s)方法去数据库查询用户
            @Override
            public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
                return new UserDetails() {
                    @Override
                    public Collection<? extends GrantedAuthority> getAuthorities() {
                        return null;
                    }

                    @Override
                    public String getPassword() {
                        return "itxsl";
                    }

                    @Override
                    public String getUsername() {
                        return "itxsl";
                    }

                    @Override
                    public boolean isAccountNonExpired() {
                        return true;
                    }

                    @Override
                    public boolean isAccountNonLocked() {
                        return true;
                    }

                    @Override
                    public boolean isCredentialsNonExpired() {
                        return true;
                    }

                    @Override
                    public boolean isEnabled() {
                        return true;
                    }
                };
            }
        }     ;
    }



    @Bean//密码编码模式，这里没使用加密,需要加密可创建一个new BCryptPasswordEncoder()返回，
    // 这里加密后，用户密码和ClientSecret都会用加密后的串进行校验密码
    public PasswordEncoder passwordEncoder(){

        return  new PasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                return charSequence.toString();
            }

            @Override
            public boolean matches(CharSequence charSequence, String s) {
                return charSequence.toString().equals(s);
            }
        };
    }

    @Override
    @Bean//定义没有password grant_type
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }*/

}
